<template>
  <el-dialog title="添加商品" :visible.sync="dialogGoodsAddVisible" :before-close="cancelDialog" >
    <el-form class="form" ref="goodsAdd" :model="form" :rules="formRules">
      <el-form-item label="商品名称: " prop="goodName">
        <el-input v-model="form.goodName"></el-input>
      </el-form-item>
      <el-form-item label="商品介绍: " prop="description">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item label="价格: " prop="price">
        <el-input v-model.number="form.price" type="number"></el-input>
      </el-form-item>



      <el-form-item label="商品图片: ">
          <br>
          <el-upload
            ref="upload"
            action="http://localhost:8081/goods/save"
            name="img"
            :class="{hide:hideUpload}"
            :headers="headers"
            list-type="picture-card"
            :auto-upload=false
            :data="form"
            :limit=limitCount
            :on-success="handleSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleChange">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="imgSaveRequest">确 定</el-button>
      <el-button @click="cancelDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
    import {goodsSave,listByShopId} from  '@/api/goods'
    import {getToken} from "@/utils/auth";
    import BMap from "@/views/BMap/index";
    export default {
      name: "GoodsAddDialog",
      //父组件 传 过来的 值
      props: {
        dialogGoodsAddVisible: {
          type: Boolean,
          default: false
        },
        dialogInfo: {
          type: Object,
          default: {}
        },
      },
      watch: {
        //监听 弹窗显示， 可以用来写 请求接口
        dialogGoodsAddVisible: function(newVal, oldVal) {},
        dialogInfo:function (newVal, oldVal) {
          this.form.shopId =newVal.id;
        }
      },
      components: {
        BMap,
      },
      data() {
        return {
          dialogImageUrl: '',
          headers:{Authorization: getToken()},
          dialogVisible: false,
          hideUpload: false,
          limitCount: 1,
          form:{
            goodName:'',
            description:'',
            price:'',
            shopId: '',
          },
          formRules: {
            goodName: [{ required: true, message: '请输入商品名称',trigger: 'blur' }],
            description: [{ required: true, message: '请输入商品描述',trigger: 'blur' }],
            price:[
              { required: true, type: 'number', min: 0,message: '请输入价格（最低消费0元）',trigger: 'blur' }
            ],
          },
        };
      },
      computed: {
        // 这里定义上传文件时携带的参数，即表单数据
        upData: function() {
          return this.form
        },
      },
      created() {},
      mounted() {},
      methods: {
        //修改父组件传过来的值
        cancelDialog() {
          this.$emit("update:dialogGoodsAddVisible", false);
        },
        imgSaveRequest(){
          this.$refs.goodsAdd.validate((valid) => {
            if(valid){
              if (!this.hideUpload){
                this.$message.error('门店头像不能为空');
              }else{
                this.$refs.upload.submit();
              }
            }
          })
        },
        listByShopIdRequest(id){
          listByShopId(id).then((response) => {
            if(response.code===200){
              this.$emit("update:dialogInfo", response.data);
            }
          });
        },
        handleRemove(file, fileList) {
          this.hideUpload = fileList.length >= this.limitCount;
        },
        handleChange(file, fileList){
          this.hideUpload = fileList.length >= this.limitCount;
        },
        handlePictureCardPreview(file) {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },
        handleSuccess(response, file, fileList){
          if(response.code===200){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.form.goodName='';
            this.form.description='';
            this.form.price='';
            this.listByShopIdRequest(this.dialogInfo.id);
            this.$emit("update:dialogGoodsAddVisible", false);
            this.$refs.upload.clearFiles();
          }else{
            this.$message.error(response.msg);
          }
        },
        handleError(err, file, fileList){
          this.$message({
            message: err,
            type: 'success'
          });
        },
        beforeAvatarUpload(file) {
          let check =true;
          this.$refs.goodsAdd.validate((valid) => {
            check =valid;
          });
          if (!check) {
            return Promise;
          }
          const isJPG = file.type === 'image/jpeg';
          const isPNG = file.type === 'image/png';
          const isWEBP = file.type === 'image/webp';
          const isLt2M = file.size / 1024 / 1024 < 5;
          if (!isJPG&&!isPNG&&!isWEBP) {
            this.$message.error('上传图片只能是 JPG, PNG,WEBP 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 5MB!');
          }
          return  (isJPG||isPNG||isWEBP) && isLt2M;
        },

      }
    };
</script>

<style lang="scss">
  .form{
    padding: 0 10px;
  }
  .dialog-footer{
    text-align: center;
  }
  .hide .el-upload--picture-card {
    display: none;
  }
  .el-form .el-select{
    width: 100%;
  }
</style>
